package com.gsit.job.flows;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.gsit.job.config.Config;
import com.gsit.job.domain.SearchType;
import com.gsit.job.domain.User;

public abstract class FlowServiceAbs  implements FlowService{
	
	protected WebDriver driver = null;
	protected SearchType searchType;
	
	
	public void execute(SearchType searchType, Boolean isTest){
		System.out.println("FlowService is starting");
		this.searchType = searchType;
		if(isTest){
			processTest();
		}else{
			start();
		}
		
	}
	
	protected void start(){
		driver = new FirefoxDriver();
		doLogin();
		sleep(1000);
		try {
			process();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		sleep(2000);
		doLogOff();
		
	}
	
	
	protected void doLogOff() {
		driver.get(Config.LOGOUT_URL);
		//driver.get("http://recruiter.monsterindia.com/v2/employer_pg.html");
		WebElement element = driver.findElement(By.linkText("Logout"));
		System.out.println("Log out .....");
		element.click();
		
	}
	
	protected void doLogin() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy 'at' HH:mm:ss");
		System.out.println("Login to your System , time " + dateFormat.format(new Date()));
		driver.get(Config.LOGIN_URL);
		
		//btn-slide
		WebElement element = driver.findElement(By.id("btn-slide"));
		element.click();
		sleep(1000);
		element = driver.findElement(By.id("login"));
		User user = Config.createUser();
		
		if (element != null) {
			element.sendKeys(user.getUserName());
		}
		element = driver.findElement(By.id("passwd"));
		if (element != null) {
			element.sendKeys(user.getPassword());
		}
		element.submit();
		
	}
	
	protected void sleep(long ms) {
		try {
			Thread.sleep(ms);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected final void callWaitForCaptcha(){
		JOptionPane optionPane = new JOptionPane("Captcha is found.");
		JDialog dialog = optionPane.createDialog("Alert.....");
		dialog.setAlwaysOnTop(true);
		dialog.setVisible(true);
		//System.out.println("Captcha is done and moving to next round ..................");
	}


	protected abstract void process()throws Exception;
	protected abstract void processTest();

}
